package com.assess.controller;

import com.assess.entity.AssessIndicatorMatrix;
import com.assess.service.AssessIndicatorMatrixService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.deductive.common.core.domain.AjaxResult;
import com.deductive.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/assess/matrix")
@Api(tags = "指标树-AHP矩阵管理")
public class AssessIndicatorMatrixController {

    @Resource
    private AssessIndicatorMatrixService matrixService;

    @PostMapping("/batch")
    @ApiOperation("批量保存某父节点的成对比较矩阵（覆盖式写入由前端自行控制）")
    public AjaxResult saveBatchMatrix(@ApiParam("父指标ID") @RequestParam Long parentId,
                                      @ApiParam("矩阵版本") @RequestParam Integer version,
                                      @ApiParam("方案/项目ID(可选)") @RequestParam(required = false) Long schemeId,
                                      @RequestBody List<AssessIndicatorMatrix> elements) {
        if (parentId == null || version == null || elements == null || elements.isEmpty()) {
            return AjaxResult.error("参数不能为空");
        }
        // 校验：对角线=1，正数；若传入下三角，亦需满足互反
        for (AssessIndicatorMatrix e : elements) {
            if (e.getIIndex() == null || e.getJIndex() == null || e.getValue() == null) {
                return AjaxResult.error("矩阵元素缺少必要字段");
            }
            if (e.getIIndex().equals(e.getJIndex()) && Math.abs(e.getValue() - 1.0) > 1e-9) {
                return AjaxResult.error("对角线元素必须为1");
            }
            if (e.getValue() <= 0) {
                return AjaxResult.error("矩阵值必须为正数");
            }
        }
        // 写入前可选择覆盖策略：此处简单策略为先删除同 parentId/version/schemeId 再插入
        elements.forEach(x -> x.setSchemeId(schemeId));
        matrixService.saveBatchMatrix(parentId, version, elements);
        return AjaxResult.success();
    }

    @GetMapping("/{id}")
    @ApiOperation("根据ID查询矩阵元素")
    public AjaxResult getById(@PathVariable Long id) {
        AssessIndicatorMatrix row = matrixService.getById(id);
        return AjaxResult.success(row);
    }

    @GetMapping("/page")
    @ApiOperation("分页查询矩阵元素")
    public TableDataInfo page(@RequestParam(defaultValue = "1") long pageNum,
                              @RequestParam(defaultValue = "10") long pageSize,
                              @RequestParam(required = false) Long parentId,
                              @RequestParam(required = false) Integer version,
                              @RequestParam(required = false) Long schemeId) {
        LambdaQueryWrapper<AssessIndicatorMatrix> qw = new LambdaQueryWrapper<>();
        qw.eq(parentId != null, AssessIndicatorMatrix::getParentId, parentId)
          .eq(version != null, AssessIndicatorMatrix::getVersion, version)
          .eq(schemeId != null, AssessIndicatorMatrix::getSchemeId, schemeId)
          .orderByAsc(AssessIndicatorMatrix::getParentId, AssessIndicatorMatrix::getVersion, AssessIndicatorMatrix::getIIndex, AssessIndicatorMatrix::getJIndex);
        Page<AssessIndicatorMatrix> page = matrixService.page(new Page<>(pageNum, pageSize), qw);
        TableDataInfo rsp = new com.deductive.common.core.page.TableDataInfo();
        rsp.setCode(com.deductive.common.constant.HttpStatus.SUCCESS);
        rsp.setMsg("查询成功");
        rsp.setRows(page.getRecords());
        rsp.setTotal(page.getTotal());
        return rsp;
    }

    @PostMapping
    @ApiOperation("新增矩阵元素")
    public AjaxResult create(@RequestBody AssessIndicatorMatrix entity) {
        boolean ok = matrixService.save(entity);
        return ok ? AjaxResult.success() : AjaxResult.error("保存失败");
    }

    @PutMapping
    @ApiOperation("修改矩阵元素")
    public com.deductive.common.core.domain.AjaxResult update(@RequestBody AssessIndicatorMatrix entity) {
        boolean ok = matrixService.updateById(entity);
        return ok ? AjaxResult.success() : AjaxResult.error("更新失败");
    }

    @DeleteMapping
    @ApiOperation("批量删除矩阵元素")
    public AjaxResult delete(@ApiParam("ID列表") @RequestParam List<Long> idList) {
        boolean ok = matrixService.removeByIds(idList);
        return ok ? AjaxResult.success() : AjaxResult.error("删除失败");
    }
}


